package com.f5.management.controller;

import com.f5.management.dao.CommunityDAO;
import com.f5.management.entity.Community;
import com.f5.management.entity.Parking;
import com.f5.management.service.ParkingService;
import com.f5.management.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("parking")
public class ParkingController {
    @Autowired
    private ParkingService parkingService;
    @Autowired
    private CommunityDAO communityDAO;

    @GetMapping("findAll")
    public List<Parking> get() {
        return parkingService.list();
    }

    @GetMapping("communities")
    public List<Community> getAllComms() {
        return communityDAO.list();
    }

    @PostMapping("saveOrUpdate")
    public Result save(@RequestBody Parking parking) {
        Result result = new Result();
        try {
            if(parking.getCommunity().getName().equals("") || parking.getCommunity().getName() == null) {
                throw new Exception();
            }

            System.out.println(parking);
            if(parking.getId() == 0) { // 保存
                parkingService.insert(parking);
                result.setMsg("保存成功");
            } else { // 更新
                parkingService.update(parking);
                result.setMsg("更新成功");
            }
        } catch (Exception e) {
            result.setMsg("操作失败，稍后再试");
            result.setStatus(false);
        }
        return result;
    }

    @GetMapping("delete")
    public Result delete(Integer id) {
        Result result = new Result();
        try {
            parkingService.delete(id);
            result.setMsg("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("删除失败");
            result.setStatus(false);
        }
        return result;
    }

    @GetMapping("findByPage")
    public Map<String, Object> findByPage(Integer pageNow, Integer pageSize) {
        Map<String, Object> result= new HashMap<>();

        pageNow = (pageNow == null ? 1 : pageNow);
        pageSize = (pageSize == null ? 4 : pageSize);
        List<Parking> parkings = parkingService.findByPage(pageNow, pageSize);

        Long count = parkingService.count();

        result.put("parkings", parkings);
        result.put("count", count);

        return result;
    }
}
